home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_06 / saks / str.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1994-04-08  |  989 b   |  65 lines

  1. Listing 5 - member function definitions for a variable-length string
  2.  
  3. //
  4. // str.cpp - a variable-length string (implementation)
  5. //
  6.  
  7. #include <assert.h>
  8.  
  9. #include "str.h"
  10.  
  11. str::str(const char *s)
  12.     {
  13.     assert(s != 0);
  14.     len = strlen(s);
  15.     ptr = strcpy(new char[len + 1], s);
  16.     }
  17.  
  18. str::str(const str &s)
  19.     {
  20.     len = s.len;
  21.     ptr = strcpy(new char[len + 1], s.ptr);
  22.     }
  23.  
  24. const str &str::operator=(const char *s)
  25.     {
  26.     assert(s != 0);
  27.     size_t n = strlen(s);
  28.     if (len != n)
  29.         {
  30.         delete [] ptr;
  31.         len = n;
  32.         ptr = new char[len + 1];
  33.         }
  34.     strcpy(ptr, s);
  35.     return *this;
  36.     }
  37.  
  38. const str &str::operator=(const str &s)
  39.     {
  40.     if (this != &s)
  41.         {
  42.         if (len != s.len)
  43.             {
  44.             delete [] ptr;
  45.             len = s.len;
  46.             ptr = new char[len + 1];
  47.             }
  48.         strcpy(ptr, s.ptr);
  49.         }
  50.     return *this;
  51.     }
  52.  
  53. ostream &operator<<(ostream &s, const str &x)
  54.     {
  55.     return s << x.ptr;
  56.     }
  57.  
  58. istream &operator>>(istream &s, str &x)
  59.     {
  60.     char buf[512];
  61.     s >> buf;
  62.     x = buf;
  63.     return s;
  64.     }
  65.